<template>
  <view class="container">
    <!-- 页签区域 -->
    <view class="tabs">
      <view 
        class="tab-item" 
        :class="{ active: currentTab === 'poop' }"
        @click="switchTab('poop')"
      >
        拉粑粑
      </view>
      <view 
        class="tab-item" 
        :class="{ active: currentTab === 'sick' }"
        @click="switchTab('sick')"
      >
        生病
      </view>
    </view>
    
    <!-- 表格区域 -->
    <view class="table-container">
      <!-- 拉粑粑页签的表格 -->
      <view v-if="currentTab === 'poop'">
        <view class="table-header">
          <text class="header-cell">日期</text>
          <text class="header-cell">时间</text>
          <text class="header-cell">操作</text>
        </view>
        
        <view class="table-body" :style="{height: tableBodyHeight + 'px'}">
          <scroll-view 
            scroll-y 
            :style="{height: '100%'}" 
            :scroll-top="scrollTop"
            v-if="sortedData.length > 0"
          >
            <view 
              v-for="(item, index) in currentPageData" 
              :key="item.id" 
              class="table-row"
            >
              <text class="table-cell editable-cell" @click="editDate(item.id)">{{ item.date }}</text>
              <text class="table-cell editable-cell" @click="editTime(item.id)">{{ item.time }}</text>
              <view class="table-cell">
                <button class="edit-btn" @click="editRecord(item.id)">编辑</button>
                <button class="delete-btn" @click="showDeleteConfirmDialog(item.id)">删除</button>
              </view>
            </view>
          </scroll-view>
          
          <view v-else class="empty-tip">
            暂无记录，点击下方"+"添加
          </view>
        </view>
      </view>
      
      <!-- 生病页签的表格 -->
      <view v-else>
        <view class="table-header sick-header">
          <text class="header-cell">起始日期</text>
          <text class="header-cell">起始时间</text>
          <text class="header-cell">结束日期</text>
          <text class="header-cell">结束时间</text>
          <text class="header-cell">操作</text>
        </view>
        
        <view class="table-body" :style="{height: tableBodyHeight + 'px'}">
          <scroll-view 
            scroll-y 
            :style="{height: '100%'}" 
            :scroll-top="scrollTop"
            v-if="sortedData.length > 0"
          >
            <view 
              v-for="(item, index) in currentPageData" 
              :key="item.id" 
              class="table-row sick-row"
            >
              <text class="table-cell editable-cell" @click="editDate(item.id)">{{ item.date }}</text>
              <text class="table-cell editable-cell" @click="editTime(item.id)">{{ item.time }}</text>
              <text class="table-cell editable-cell" @click="editEndDate(item.id)">{{ item.endDate || '未设置' }}</text>
              <text class="table-cell editable-cell" @click="editEndTime(item.id)">{{ item.endTime || '未设置' }}</text>
              <view class="table-cell">
                <button class="edit-btn" @click="openSickEditor(item.id)">编辑</button>
                <button class="delete-btn" @click="showDeleteConfirmDialog(item.id)">删除</button>
              </view>
            </view>
          </scroll-view>
          
          <view v-else class="empty-tip">
            暂无记录，点击下方"+"添加
          </view>
        </view>
      </view>
    </view>
    
    <!-- 底部按钮区域 -->
    <view class="button-container">
      <view class="pagination-buttons">
        <!-- 清除按钮（X）放在上一页按钮前面 -->
        <button class="clear-btn-x" @click="showClearConfirm">X</button>
        
        <button 
          class="page-btn" 
          :disabled="!hasPrevPage" 
          @click="prevPage"
        >
          上一页
        </button>
        <text class="page-info">{{ pageInfoText }}</text>
        <button 
          class="page-btn" 
          :disabled="!hasNextPage" 
          @click="nextPage"
        >
          下一页
        </button>
      </view>
      
      <button class="add-btn" @click="addRecord">+</button>
    </view>
    
    <!-- 日期时间选择器 -->
    <view v-if="showPicker" class="picker-modal">
      <view class="picker-mask" @click="cancelEdit"></view>
      <view class="picker-content">
        <view class="picker-header">
          <text class="picker-title">修改{{ editingField === 'date' ? '日期' : editingField === 'endDate' ? '结束日期' : '时间' }}</text>
          <view class="picker-actions">
            <button class="picker-btn cancel" @click="cancelEdit">取消</button>
            <button class="picker-btn confirm" @click="confirmEdit">确定</button>
          </view>
        </view>
        
        <picker-view 
          v-if="editingField === 'date' || editingField === 'endDate'" 
          class="picker-view" 
          :value="pickerValue" 
          @change="onDateChange"
          indicator-style="height: 50px;"
        >
          <picker-view-column>
            <view class="picker-item" v-for="year in years" :key="year">{{ year }}年</view>
          </picker-view-column>
          <picker-view-column>
            <view class="picker-item" v-for="month in months" :key="month">{{ month }}月</view>
          </picker-view-column>
          <picker-view-column>
            <view class="picker-item" v-for="day in days" :key="day">{{ day }}日</view>
          </picker-view-column>
        </picker-view>
        
        <picker-view 
          v-else-if="editingField === 'time' || editingField === 'endTime'" 
          class="picker-view" 
          :value="timePickerValue" 
          @change="onTimeChange"
          indicator-style="height: 50px;"
        >
          <picker-view-column>
            <view class="picker-item" v-for="hour in hours" :key="hour">{{ hour }}时</view>
          </picker-view-column>
          <picker-view-column>
            <view class="picker-item" v-for="minute in minutes" :key="minute">{{ minute }}分</view>
          </picker-view-column>
        </picker-view>
      </view>
    </view>
    
    <!-- 文本编辑弹窗 -->
    <view v-if="showTextEditor" class="editor-modal">
      <view class="editor-mask" @click="cancelTextEdit"></view>
      <view class="editor-content">
        <view class="editor-header">
          <text class="editor-title">编辑{{ textEditorTitle }}</text>
          <view class="editor-actions">
            <button class="editor-btn cancel" @click="cancelTextEdit">取消</button>
            <button class="editor-btn confirm" @click="confirmTextEdit">确定</button>
          </view>
        </view>
        
        <textarea 
          class="editor-textarea" 
          v-model="tempText" 
          :placeholder="`请输入${textEditorTitle}`"
          maxlength="500"
        ></textarea>
      </view>
    </view>
    
    <!-- 生病信息编辑页面 -->
    <view v-if="showSickEditor" class="sick-editor-modal">
      <view class="sick-editor-mask" @click="closeSickEditor"></view>
      <view class="sick-editor-content">
        <view class="sick-editor-header">
          <text class="sick-editor-title">编辑生病信息</text>
          <button class="close-btn" @click="closeSickEditor">×</button>
        </view>
        
        <view class="sick-editor-form">
          <view class="form-group">
            <text class="form-label">起始日期</text>
            <view class="form-input" @click="editStartDate">
              {{ editingRecord.date || '点击选择日期' }}
            </view>
          </view>
          
          <view class="form-group">
            <text class="form-label">起始时间</text>
            <view class="form-input" @click="editStartTime">
              {{ editingRecord.time || '点击选择时间' }}
            </view>
          </view>
          
          <view class="form-group">
            <text class="form-label">结束日期</text>
            <view class="form-input" @click="editRecordEndDate">
              {{ editingRecord.endDate || '点击选择日期' }}
            </view>
          </view>
          
          <view class="form-group">
            <text class="form-label">结束时间</text>
            <view class="form-input" @click="editRecordEndTime">
              {{ editingRecord.endTime || '点击选择时间' }}
            </view>
          </view>
          
          <view class="form-group">
            <text class="form-label">症状</text>
            <textarea 
              class="form-textarea" 
              v-model="editingRecord.symptoms" 
              placeholder="请输入症状"
              maxlength="500"
            ></textarea>
          </view>
          
          <view class="form-group">
            <text class="form-label">诊断结果</text>
            <textarea 
              class="form-textarea" 
              v-model="editingRecord.diagnosis" 
              placeholder="请输入诊断结果"
              maxlength="500"
            ></textarea>
          </view>
          
          <view class="form-group">
            <text class="form-label">治疗方法</text>
            <textarea 
              class="form-textarea" 
              v-model="editingRecord.treatment" 
              placeholder="请输入治疗方法"
              maxlength="500"
            ></textarea>
          </view>
        </view>
        
        <view class="sick-editor-actions">
          <button class="sick-editor-btn cancel" @click="closeSickEditor">取消</button>
          <button class="sick-editor-btn confirm" @click="saveSickRecord">保存</button>
        </view>
      </view>
    </view>
    
    <!-- 删除确认弹窗 -->
    <view v-if="showDeleteConfirm" class="delete-confirm-modal">
      <view class="delete-confirm-mask" @click="cancelDelete"></view>
      <view class="delete-confirm-content">
        <view class="delete-confirm-header">
          <text class="delete-confirm-title">确认删除</text>
        </view>
        <view class="delete-confirm-body">
          <text class="delete-confirm-message">确定要删除这条记录吗？此操作不可恢复。</text>
        </view>
        <view class="delete-confirm-actions">
          <button class="delete-confirm-btn cancel" @click="cancelDelete">取消</button>
          <button class="delete-confirm-btn confirm" @click="confirmDelete">删除</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentTab: 'poop', // 当前页签
      currentPage: 1, // 当前页码
      tableBodyHeight: 400, // 表格主体高度
      rowHeight: 50, // 每行高度
      scrollTop: 0, // 滚动位置
      
      // 数据存储
      poopData: [], // 拉粑粑数据
      sickData: [], // 生病数据
      
      // 编辑相关状态
      showPicker: false, // 是否显示选择器
      showTextEditor: false, // 是否显示文本编辑器
      showSickEditor: false, // 是否显示生病信息编辑页面
      editingId: null, // 正在编辑的记录ID
      editingField: 'date', // 正在编辑的字段：date/time/endDate/endTime/symptoms/diagnosis/treatment
      tempDate: '', // 临时存储的日期
      tempTime: '', // 临时存储的时间
      tempText: '', // 临时存储的文本内容
      textEditorTitle: '', // 文本编辑器标题
      pickerValue: [0, 0, 0], // 日期选择器值
      timePickerValue: [0, 0], // 时间选择器值
      
      // 生病信息编辑页面相关
      editingRecord: {}, // 正在编辑的记录
      
      // 删除确认弹窗相关
      showDeleteConfirm: false, // 是否显示删除确认弹窗
      deletingId: null, // 正在删除的记录ID
      
      // 选择器数据
      years: [],
      months: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
      days: [],
      hours: [],
      minutes: []
    }
  },
  
  computed: {
    // 当前页签的数据（按时间戳从新到旧排序）
    currentData() {
      const data = this.currentTab === 'poop' ? this.poopData : this.sickData
      // 使用计算属性确保数据始终按时间戳降序排列[5](@ref)
      return [...data].sort((a, b) => b.timestamp - a.timestamp)
    },
    
    // 排序后的数据（确保始终按时间从新到旧）
    sortedData() {
      return this.currentData
    },
    
    // 每页显示行数（根据表格高度和行高动态计算）
    pageSize() {
      return Math.floor(this.tableBodyHeight / this.rowHeight)
    },
    
    // 当前页的数据（从排序后的数据中切片）
    currentPageData() {
      const startIndex = (this.currentPage - 1) * this.pageSize
      return this.sortedData.slice(startIndex, startIndex + this.pageSize)
    },
    
    // 总页数
    totalPages() {
      return Math.ceil(this.sortedData.length / this.pageSize) || 1
    },
    
    // 是否有上一页
    hasPrevPage() {
      return this.currentPage > 1
    },
    
    // 是否有下一页
    hasNextPage() {
      return this.currentPage < this.totalPages
    },
    
    // 页面信息文本
    pageInfoText() {
      if (this.totalPages <= 1) {
        return `共 ${this.sortedData.length} 条`
      }
      return `第 ${this.currentPage}/${this.totalPages} 页`
    }
  },
  
  onLoad() {
    // 从本地存储加载数据
    this.loadData()
    // 初始化选择器数据
    this.initPickerData()
  },
  
  onReady() {
    // 计算表格主体高度
    this.calculateTableHeight()
  },
  
  methods: {
    // 初始化选择器数据
    initPickerData() {
      // 初始化年份（当前年前后5年）
      const currentYear = new Date().getFullYear()
      for (let i = currentYear - 2; i <= currentYear + 3; i++) {
        this.years.push(i)
      }
      
      // 初始化日期（1-31）
      for (let i = 1; i <= 31; i++) {
        this.days.push(i < 10 ? '0' + i : i.toString())
      }
      
      // 初始化小时（0-23）
      for (let i = 0; i < 24; i++) {
        this.hours.push(i < 10 ? '0' + i : i.toString())
      }
      
      // 初始化分钟（0-59）
      for (let i = 0; i < 60; i++) {
        this.minutes.push(i < 10 ? '0' + i : i.toString())
      }
    },
    
    // 计算表格主体高度
    calculateTableHeight() {
      const systemInfo = uni.getSystemInfoSync()
      const windowHeight = systemInfo.windowHeight
      
      const tabsHeight = 50
      const tableHeaderHeight = 50
      const buttonContainerHeight = 100
      const margins = 40
      
      this.tableBodyHeight = windowHeight - tabsHeight - tableHeaderHeight - buttonContainerHeight - margins
    },
    
    // 切换页签
    switchTab(tab) {
      this.currentTab = tab
      this.currentPage = 1
      this.scrollTop = 0 // 重置滚动位置
    },
    
    // 添加记录
    addRecord() {
      const now = new Date()
      
      // 格式化日期为"2025-10-18"格式
      const year = now.getFullYear()
      const month = (now.getMonth() + 1).toString().padStart(2, '0')
      const day = now.getDate().toString().padStart(2, '0')
      const date = `${year}-${month}-${day}`
      
      // 格式化时间为"21:00"格式，包含实际分钟
      const hours = now.getHours().toString().padStart(2, '0')
      const minutes = now.getMinutes().toString().padStart(2, '0')
      const time = `${hours}:${minutes}`
      
      // 生成唯一ID
      const id = 'id_' + new Date().getTime() + '_' + Math.random().toString(36).substr(2, 9)
      
      // 根据当前页签创建不同结构的记录
      let newRecord = {
        id: id,
        date: date,
        time: time,
        timestamp: now.getTime()
      }
      
      // 如果是生病页签，添加额外的字段
      if (this.currentTab === 'sick') {
        newRecord = {
          ...newRecord,
          endDate: '', // 结束日期，初始为空
          endTime: '', // 结束时间，初始为空
          symptoms: '', // 症状，初始为空
          diagnosis: '', // 诊断结果，初始为空
          treatment: '' // 治疗方法，初始为空
        }
      }
      
      // 根据当前页签添加到对应数据数组的开头[6](@ref)
      if (this.currentTab === 'poop') {
        this.poopData.unshift(newRecord)
      } else {
        this.sickData.unshift(newRecord)
      }
      
      // 保存到本地存储
      this.saveData()
      
      // 添加后回到第一页并重置滚动位置
      this.currentPage = 1
      this.scrollTop = 0
      
      uni.showToast({
        title: '记录添加成功',
        icon: 'success',
        duration: 1000
      })
    },
    
    // 编辑记录（完整编辑）
    editRecord(id) {
      const record = this.currentData.find(item => item.id === id)
      if (!record) return
      
      this.editingId = id
      this.tempDate = record.date
      this.tempTime = record.time
      this.editingField = 'date'
      
      // 设置日期选择器初始值
      this.setDatePickerValue(record.date)
      this.showPicker = true
    },
    
    // 编辑日期
    editDate(id) {
      const record = this.currentData.find(item => item.id === id)
      if (!record) return
      
      this.editingId = id
      this.tempDate = record.date
      this.tempTime = record.time
      this.editingField = 'date'
      
      // 设置日期选择器初始值
      this.setDatePickerValue(record.date)
      this.showPicker = true
    },
    
    // 编辑时间
    editTime(id) {
      const record = this.currentData.find(item => item.id === id)
      if (!record) return
      
      this.editingId = id
      this.tempDate = record.date
      this.tempTime = record.time
      this.editingField = 'time'
      
      // 设置时间选择器初始值
      this.setTimePickerValue(record.time)
      this.showPicker = true
    },
    
    // 编辑结束日期
    editEndDate(id) {
      const record = this.currentData.find(item => item.id === id)
      if (!record) return
      
      this.editingId = id
      this.tempDate = record.endDate || record.date // 如果没有结束日期，使用起始日期作为默认值
      this.editingField = 'endDate'
      
      // 设置日期选择器初始值
      this.setDatePickerValue(this.tempDate)
      this.showPicker = true
    },
    
    // 编辑结束时间
    editEndTime(id) {
      const record = this.currentData.find(item => item.id === id)
      if (!record) return
      
      this.editingId = id
      this.tempTime = record.endTime || record.time // 如果没有结束时间，使用起始时间作为默认值
      this.editingField = 'endTime'
      
      // 设置时间选择器初始值
      this.setTimePickerValue(this.tempTime)
      this.showPicker = true
    },
    
    // 编辑症状
    editSymptoms(id) {
      const record = this.currentData.find(item => item.id === id)
      if (!record) return
      
      this.editingId = id
      this.tempText = record.symptoms || ''
      this.textEditorTitle = '症状'
      this.editingField = 'symptoms'
      this.showTextEditor = true
    },
    
    // 编辑诊断结果
    editDiagnosis(id) {
      const record = this.currentData.find(item => item.id === id)
      if (!record) return
      
      this.editingId = id
      this.tempText = record.diagnosis || ''
      this.textEditorTitle = '诊断结果'
      this.editingField = 'diagnosis'
      this.showTextEditor = true
    },
    
    // 编辑治疗方法
    editTreatment(id) {
      const record = this.currentData.find(item => item.id === id)
      if (!record) return
      
      this.editingId = id
      this.tempText = record.treatment || ''
      this.textEditorTitle = '治疗方法'
      this.editingField = 'treatment'
      this.showTextEditor = true
    },
    
    // 确认文本编辑
    confirmTextEdit() {
      if (!this.editingId) {
        this.showTextEditor = false
        return
      }
      
      // 更新记录
      const dataArray = this.currentData
      const recordIndex = dataArray.findIndex(item => item.id === this.editingId)
      
      if (recordIndex !== -1) {
        dataArray[recordIndex][this.editingField] = this.tempText
        
        // 保存到本地存储
        this.saveData()
        
        uni.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1000
        })
      }
      
      this.showTextEditor = false
      this.editingId = null
      this.tempText = ''
    },
    
    // 取消文本编辑
    cancelTextEdit() {
      this.showTextEditor = false
      this.editingId = null
      this.tempText = ''
    },
    
    // 设置日期选择器初始值
    setDatePickerValue(dateString) {
      if (!dateString) {
        // 如果日期为空，使用当前日期
        const now = new Date()
        const year = now.getFullYear()
        const month = (now.getMonth() + 1).toString().padStart(2, '0')
        const day = now.getDate().toString().padStart(2, '0')
        dateString = `${year}-${month}-${day}`
      }
      
      const dateParts = dateString.split('-')
      const yearIndex = this.years.indexOf(parseInt(dateParts[0]))
      const monthIndex = this.months.indexOf(dateParts[1]) 
      const dayIndex = this.days.indexOf(dateParts[2]) 
      
      this.pickerValue = [
        yearIndex >= 0 ? yearIndex : 2,
        monthIndex >= 0 ? monthIndex : 0,
        dayIndex >= 0 ? dayIndex : 0
      ]
    },
    
    // 设置时间选择器初始值
    setTimePickerValue(timeString) {
      if (!timeString) {
        // 如果时间为空，使用当前时间
        const now = new Date()
        const hours = now.getHours().toString().padStart(2, '0')
        const minutes = now.getMinutes().toString().padStart(2, '0')
        timeString = `${hours}:${minutes}`
      }
      
      const timeParts = timeString.split(':')
      const hourIndex = this.hours.indexOf(timeParts[0])
      const minuteIndex = this.minutes.indexOf(timeParts[1])
      
      this.timePickerValue = [
        hourIndex >= 0 ? hourIndex : 0,
        minuteIndex >= 0 ? minuteIndex : 0
      ]
    },
    
    // 日期选择变化
    onDateChange(e) {
      const value = e.detail.value
      const year = this.years[value[0]]
      const month = this.months[value[1]]
      const day = this.days[value[2]]
      
      this.tempDate = `${year}-${month}-${day}`
      this.pickerValue = value
    },
    
    // 时间选择变化
    onTimeChange(e) {
      const value = e.detail.value
      const hour = this.hours[value[0]]
      const minute = this.minutes[value[1]]
      
      this.tempTime = `${hour}:${minute}`
      this.timePickerValue = value
    },
    
    // 确认编辑
    confirmEdit() {
      // 如果是在生病信息编辑页面中编辑日期时间
      if (this.showSickEditor) {
        // 更新编辑记录中的日期时间
        if (this.editingField === 'date') {
          // 如果tempDate为空或null，设置为当前日期
          if (!this.tempDate) {
            this.tempDate = new Date().toISOString().split('T')[0]
          }
          
          this.editingRecord.date = this.tempDate
          // 如果是编辑起始日期，继续编辑起始时间
          this.editingField = 'time'
          this.setTimePickerValue(this.editingRecord.time)
          return
        } else if (this.editingField === 'time') {
          this.editingRecord.time = this.tempTime
        } else if (this.editingField === 'endDate') {
          // 验证结束日期不得早于起始日期
          const startDate = new Date(this.editingRecord.date)
		  
		  // 如果tempDate为空或null，设置为当前日期
		  if (!this.tempDate) {
		    this.tempDate = new Date().toISOString().split('T')[0]
		  }
		  
          const endDate = new Date(this.tempDate)

          // 只比较日期部分，忽略时间部分
          const startDateOnly = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate())
          const endDateOnly = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate())
		  
          // 结束日期不能早于起始日期，但可以等于起始日期
          if (endDateOnly < startDateOnly) {
            uni.showToast({
              title: '结束日期不能早于起始日期',
              icon: 'none',
              duration: 2000
            })
            this.showPicker = false
            return
          }
          
          this.editingRecord.endDate = this.tempDate
          // 立即更新原始数据
          const recordIndex = this.sickData.findIndex(item => item.id === this.editingRecord.id)
          if (recordIndex !== -1) {
            this.sickData[recordIndex].endDate = this.tempDate
            this.saveData()
          }
        } else if (this.editingField === 'endTime') {
          // 验证结束时间不得早于起始时间（当日期相同时）
          const startDate = new Date(this.editingRecord.date)
          const endDate = new Date(this.editingRecord.endDate || this.editingRecord.date)
          
          // 创建完整的时间对象进行比较
          const startDateTime = new Date(`${this.editingRecord.date} ${this.editingRecord.time}`)
          const endDateTime = new Date(`${this.editingRecord.endDate || this.editingRecord.date} ${this.tempTime}`)
          
          if (endDateTime < startDateTime) {
            uni.showToast({
              title: '结束时间不能早于起始时间',
              icon: 'none',
              duration: 2000
            })
            this.showPicker = false
            return
          }
          
          this.editingRecord.endTime = this.tempTime
          // 立即更新原始数据
          const recordIndex = this.sickData.findIndex(item => item.id === this.editingRecord.id)
          if (recordIndex !== -1) {
            this.sickData[recordIndex].endTime = this.tempTime
            this.saveData()
          }
        }
        
        this.showPicker = false
        return
      }
      
      // 原有的表格中编辑逻辑
      if (!this.editingId) {
        this.showPicker = false
        return
      }
      
      // 如果是日期编辑，继续编辑时间
      if (this.editingField === 'date') {
        this.editingField = 'time'
        this.setTimePickerValue(this.tempTime)
        return
      }
      
      // 更新记录
      const dataArray = this.currentTab === 'poop' ? this.poopData : this.sickData
      const recordIndex = dataArray.findIndex(item => item.id === this.editingId)
      
      if (recordIndex !== -1) {
        // 根据编辑字段更新不同的数据
        if (this.editingField === 'time') {
          // 如果tempDate为空或null，设置为当前日期
          if (!this.tempDate) {
            this.tempDate = new Date().toISOString().split('T')[0]
          }
          
          // 更新起始时间
          dataArray[recordIndex].date = this.tempDate
          dataArray[recordIndex].time = this.tempTime
          
          // 创建新的时间戳
          const newDateTimeString = `${this.tempDate} ${this.tempTime}`
          const newTimestamp = new Date(newDateTimeString).getTime()
          dataArray[recordIndex].timestamp = newTimestamp
          
          // 重新排序（按时间倒序）
          dataArray.sort((a, b) => b.timestamp - a.timestamp)
        } else if (this.editingField === 'endDate') {
          // 验证结束日期不得早于起始日期
          const startDate = new Date(dataArray[recordIndex].date)
          
          // 如果tempDate为空或null，设置为当前日期
          if (!this.tempDate) {
            this.tempDate = new Date().toISOString().split('T')[0]
          }
          
          const endDate = new Date(this.tempDate)
          
          // 只比较日期部分，忽略时间部分
          const startDateOnly = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate())
          const endDateOnly = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate())
          
          // 结束日期不能早于起始日期，但可以等于起始日期
          if (endDateOnly < startDateOnly) {
            uni.showToast({
              title: '结束日期不能早于起始日期',
              icon: 'none',
              duration: 2000
            })
            this.showPicker = false
            return
          }
          
          // 更新结束日期
          dataArray[recordIndex].endDate = this.tempDate
        } else if (this.editingField === 'endTime') {
          // 验证结束时间不得早于起始时间（当日期相同时）
          const startDate = new Date(dataArray[recordIndex].date)
          const endDate = new Date(dataArray[recordIndex].endDate || dataArray[recordIndex].date)
          
          // 创建完整的时间对象进行比较
          const startDateTime = new Date(`${dataArray[recordIndex].date} ${dataArray[recordIndex].time}`)
          const endDateTime = new Date(`${dataArray[recordIndex].endDate || dataArray[recordIndex].date} ${this.tempTime}`)
          
          if (endDateTime < startDateTime) {
            uni.showToast({
              title: '结束时间不能早于起始时间',
              icon: 'none',
              duration: 2000
            })
            this.showPicker = false
            return
          }
          
          // 更新结束时间
          dataArray[recordIndex].endTime = this.tempTime
        }
        
        // 保存到本地存储
        this.saveData()
        
        uni.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1000
        })
      }
      
      this.showPicker = false
      this.editingId = null
    },
    
    // 取消编辑
    cancelEdit() {
      this.showPicker = false
      this.editingId = null
    },
    
    // 上一页
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
        this.scrollTop = 0 // 翻页时重置滚动位置到顶部
      }
    },
    
    // 下一页
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++
        this.scrollTop = 0 // 翻页时重置滚动位置到顶部
      }
    },
    
    // 显示清除确认对话框
    showClearConfirm() {
      const tabName = this.currentTab === 'poop' ? '拉粑粑' : '生病'
      uni.showModal({
        title: '确认清除',
        content: `确定要清除${tabName}页签的所有数据吗？此操作不可恢复！`,
        confirmColor: '#ff4d4f',
        success: (res) => {
          if (res.confirm) {
            this.clearCurrentTabData()
          }
        }
      })
    },
    
    // 清除当前页签数据
    clearCurrentTabData() {
      if (this.currentTab === 'poop') {
        this.poopData = []
      } else {
        this.sickData = []
      }
      
      this.currentPage = 1
      this.scrollTop = 0
      
      // 清除本地存储中对应的数据
      try {
        const tabName = this.currentTab === 'poop' ? 'poopData' : 'sickData'
        uni.removeStorageSync(tabName)
      } catch (e) {
        console.error('清除本地存储失败:', e)
      }
      
      uni.showToast({
        title: '数据已清除',
        icon: 'success',
        duration: 2000
      })
    },
    
    // 保存数据到本地存储
    saveData() {
      try {
        uni.setStorageSync('poopData', this.poopData)
        uni.setStorageSync('sickData', this.sickData)
      } catch (e) {
        console.error('保存数据失败:', e)
      }
    },
    
    // 从本地存储加载数据
    loadData() {
      try {
        const poopData = uni.getStorageSync('poopData')
        const sickData = uni.getStorageSync('sickData')
        
        if (poopData) {
          this.poopData = poopData
          // 为旧数据添加ID（兼容性处理）
          this.poopData.forEach(item => {
            if (!item.id) {
              item.id = 'id_' + item.timestamp + '_' + Math.random().toString(36).substr(2, 9)
            }
          })
          // 加载后立即排序[5](@ref)
          this.poopData.sort((a, b) => b.timestamp - a.timestamp)
        }
        
        if (sickData) {
          this.sickData = sickData
          this.sickData.forEach(item => {
            if (!item.id) {
              item.id = 'id_' + item.timestamp + '_' + Math.random().toString(36).substr(2, 9)
            }
            // 为旧数据添加新字段（兼容性处理）
            if (item.endDate === undefined) {
              item.endDate = ''
            }
            if (item.endTime === undefined) {
              item.endTime = ''
            }
            if (item.symptoms === undefined) {
              item.symptoms = ''
            }
            if (item.diagnosis === undefined) {
              item.diagnosis = ''
            }
            if (item.treatment === undefined) {
              item.treatment = ''
            }
          })
          // 加载后立即排序[5](@ref)
          this.sickData.sort((a, b) => b.timestamp - a.timestamp)
        }
      } catch (e) {
        console.error('加载数据失败:', e)
      }
    },
    
    // 打开生病信息编辑页面
    openSickEditor(id) {
      const record = this.sickData.find(item => item.id === id)
      if (!record) return
      
      // 创建记录副本，避免直接修改原数据
      this.editingRecord = {
        id: record.id,
        date: record.date,
        time: record.time,
        endDate: record.endDate || '',
        endTime: record.endTime || '',
        symptoms: record.symptoms || '',
        diagnosis: record.diagnosis || '',
        treatment: record.treatment || '',
        timestamp: record.timestamp
      }
      
      this.showSickEditor = true
    },
    
    // 关闭生病信息编辑页面
    closeSickEditor() {
      this.showSickEditor = false
      this.editingRecord = {}
    },
    
    // 编辑起始日期
    editStartDate() {
      this.editingField = 'date'
      this.setDatePickerValue(this.editingRecord.date)
      this.showPicker = true
    },
    
    // 编辑起始时间
    editStartTime() {
      this.editingField = 'time'
      this.setTimePickerValue(this.editingRecord.time)
      this.showPicker = true
    },
    
    // 编辑结束日期
    editRecordEndDate() {
      this.editingField = 'endDate'
      this.setDatePickerValue(this.editingRecord.endDate || this.editingRecord.date)
      this.showPicker = true
    },
    
    // 编辑结束时间
    editRecordEndTime() {
      this.editingField = 'endTime'
      this.setTimePickerValue(this.editingRecord.endTime || this.editingRecord.time)
      this.showPicker = true
    },
    
    // 保存生病记录
    saveSickRecord() {
      if (!this.editingRecord.id) return
      
      // 验证结束日期不得早于起始日期
      if (this.editingRecord.endDate) {
        const startDate = new Date(this.editingRecord.date)
        const endDate = new Date(this.editingRecord.endDate)
        
        // 只比较日期部分，忽略时间部分
        const startDateOnly = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate())
        const endDateOnly = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate())
        
        // 结束日期不能早于起始日期，但可以等于起始日期
        if (endDateOnly < startDateOnly) {
          uni.showToast({
            title: '结束日期不能早于起始日期',
            icon: 'none',
            duration: 2000
          })
          return
        }
      }
      
      // 验证结束时间不得早于起始时间（当有结束时间时）
      if (this.editingRecord.endTime) {
        // 创建完整的时间对象进行比较
        const startDateTime = new Date(`${this.editingRecord.date} ${this.editingRecord.time}`)
        const endDateTime = new Date(`${this.editingRecord.endDate || this.editingRecord.date} ${this.editingRecord.endTime}`)
        
        if (endDateTime < startDateTime) {
          uni.showToast({
            title: '结束时间不能早于起始时间',
            icon: 'none',
            duration: 2000
          })
          return
        }
      }
      
      // 更新原始数据
      const recordIndex = this.sickData.findIndex(item => item.id === this.editingRecord.id)
      if (recordIndex !== -1) {
        // 保存原始的起始日期和时间，用于比较
        const originalDate = this.sickData[recordIndex].date
        const originalTime = this.sickData[recordIndex].time
        
        // 更新所有字段
        this.sickData[recordIndex] = {
          ...this.sickData[recordIndex],
          date: this.editingRecord.date,
          time: this.editingRecord.time,
          endDate: this.editingRecord.endDate,
          endTime: this.editingRecord.endTime,
          symptoms: this.editingRecord.symptoms,
          diagnosis: this.editingRecord.diagnosis,
          treatment: this.editingRecord.treatment
        }
        
        // 如果起始日期或时间有变化，更新时间戳并重新排序
        if (originalDate !== this.editingRecord.date || 
            originalTime !== this.editingRecord.time) {
          const newDateTimeString = `${this.editingRecord.date} ${this.editingRecord.time}`
          const newTimestamp = new Date(newDateTimeString).getTime()
          this.sickData[recordIndex].timestamp = newTimestamp
          
          // 重新排序（按时间倒序）
          this.sickData.sort((a, b) => b.timestamp - a.timestamp)
        }
        
        // 保存到本地存储
        this.saveData()
        
        uni.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 1000
        })
        
        // 关闭编辑页面
        this.closeSickEditor()
      }
    },
    
    // 显示删除确认弹窗
    showDeleteConfirmDialog(id) {
      this.deletingId = id
      this.showDeleteConfirm = true
    },
    
    // 取消删除
    cancelDelete() {
      this.showDeleteConfirm = false
      this.deletingId = null
    },
    
    // 确认删除
    confirmDelete() {
      if (!this.deletingId) return
      
      // 根据当前页签从对应的数据数组中删除记录
      if (this.currentTab === 'poop') {
        const index = this.poopData.findIndex(item => item.id === this.deletingId)
        if (index !== -1) {
          this.poopData.splice(index, 1)
        }
      } else {
        const index = this.sickData.findIndex(item => item.id === this.deletingId)
        if (index !== -1) {
          this.sickData.splice(index, 1)
        }
      }
      
      // 保存到本地存储
      this.saveData()
      
      // 如果当前页没有数据了，返回上一页
      if (this.currentPageData.length === 0 && this.currentPage > 1) {
        this.currentPage--
      }
      
      // 关闭删除确认弹窗
      this.showDeleteConfirm = false
      this.deletingId = null
      
      // 显示删除成功提示
      uni.showToast({
        title: '删除成功',
        icon: 'success',
        duration: 1000
      })
    }
  },
}
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

/* 页签样式 */
.tabs {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 32rpx;
  color: #666;
  border-bottom: 4rpx solid transparent;
  transition: all 0.3s;
}

.tab-item.active {
  color: #007AFF;
  border-bottom-color: #007AFF;
  font-weight: bold;
}

/* 表格样式 */
.table-container {
  flex: 1;
  background-color: #fff;
  margin: 20rpx;
  border-radius: 10rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
  display: flex;
  flex-direction: column;
}

.table-header {
  display: flex;
  background-color: #f0f0f0;
  border-bottom: 1px solid #e0e0e0;
  flex-shrink: 0;
}

.header-cell {
  flex: 1;
  padding: 24rpx 20rpx;
  text-align: center;
  font-weight: bold;
  color: #333;
  font-size: 30rpx;
}

.table-body {
  flex: 1;
  overflow: hidden;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  height: 100rpx;
  align-items: center;
}

.table-row:last-child {
  border-bottom: none;
}

.table-cell {
  flex: 1;
  padding: 24rpx 10rpx;
  text-align: center;
  color: #555;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: nowrap;
}

/* 操作列特殊样式 */
.table-cell:last-child {
  padding: 10rpx 5rpx;
  justify-content: center;
  gap: 5rpx;
}

/* 可编辑单元格样式 */
.editable-cell {
  color: #007AFF;
  text-decoration: underline;
  cursor: pointer;
}

.editable-cell:active {
  background-color: #f0f0f0;
}

/* 编辑按钮样式 */
.edit-btn {
  padding: 6rpx 12rpx;
  font-size: 22rpx;
  background-color: #007AFF;
  color: white;
  border: none;
  border-radius: 6rpx;
  margin-right: 6rpx;
}

.empty-tip {
  text-align: center;
  padding: 60rpx 20rpx;
  color: #999;
  font-size: 28rpx;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 按钮区域样式 */
.button-container {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  border-top: 1px solid #e0e0e0;
  flex-shrink: 0;
}

.pagination-buttons {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.page-btn {
  padding: 12rpx 30rpx;
  font-size: 26rpx;
  background-color: #f0f0f0;
  border: none;
  border-radius: 8rpx;
  color: #333;
}

.page-btn:disabled {
  color: #ccc;
  background-color: #f8f8f8;
}

.page-info {
  font-size: 26rpx;
  color: #666;
}

.add-btn {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #007AFF;
  color: white;
  font-size: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 30rpx;
  border: none;
  box-shadow: 0 4rpx 10rpx rgba(0,122,255,0.3);
}

/* 清除按钮样式（X） */
.clear-btn-x {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: #ff4d4f;
  color: white;
  font-size: 28rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  margin-right: 20rpx;
  box-shadow: 0 2rpx 6rpx rgba(255, 77, 79, 0.3);
}

/* 日期时间选择器样式 */
.picker-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1099;
  display: flex;
  align-items: flex-end;
}

.picker-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.picker-content {
  position: relative;
  width: 100%;
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  padding: 30rpx;
  box-sizing: border-box;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.picker-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.picker-actions {
  display: flex;
}

.picker-btn {
  padding: 10rpx 20rpx;
  font-size: 28rpx;
  border: none;
  background: none;
  margin-left: 20rpx;
}

.picker-btn.cancel {
  color: #666;
}

.picker-btn.confirm {
  color: #007AFF;
}

.picker-view {
  width: 100%;
  height: 400rpx;
}

.picker-item {
  line-height: 50px;
  text-align: center;
  font-size: 30rpx;
}

/* 生病页签特殊样式 */
.sick-header .header-cell {
  font-size: 26rpx;
  padding: 20rpx 10rpx;
}

.sick-row {
  height: 120rpx; /* 生病页签行高增加，以容纳更多内容 */
}

.sick-row .table-cell {
  font-size: 24rpx;
  padding: 16rpx 5rpx;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 生病页签操作列特殊样式 */
.sick-row .table-cell:last-child {
  padding: 8rpx 2rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 3rpx;
  word-break: keep-all;
  -webkit-line-clamp: unset;
  -webkit-box-orient: unset;
}

/* 文本编辑弹窗样式 */
.editor-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1099;
  display: flex;
  align-items: center;
  justify-content: center;
}

.editor-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.editor-content {
  position: relative;
  width: 90%;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-sizing: border-box;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.editor-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.editor-actions {
  display: flex;
}

.editor-btn {
  padding: 10rpx 20rpx;
  font-size: 28rpx;
  border: none;
  background: none;
  margin-left: 20rpx;
}

.editor-btn.cancel {
  color: #666;
}

.editor-btn.confirm {
  color: #007AFF;
}

.editor-textarea {
  width: 100%;
  height: 300rpx;
  border: 1px solid #e0e0e0;
  border-radius: 10rpx;
  padding: 20rpx;
  font-size: 28rpx;
  line-height: 1.5;
  box-sizing: border-box;
}

/* 生病信息编辑页面样式 */
.sick-editor-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.sick-editor-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.sick-editor-content {
  position: relative;
  width: 90%;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-sizing: border-box;
  max-height: 85vh;
  display: flex;
  flex-direction: column;
}

.sick-editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 20rpx;
}

.sick-editor-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: #f5f5f5;
  color: #666;
  font-size: 32rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
}

.sick-editor-form {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 30rpx;
}

.form-group {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 30rpx;
  color: #333;
  margin-bottom: 15rpx;
  font-weight: bold;
}

.form-input {
  width: 100%;
  height: 80rpx;
  border: 1px solid #e0e0e0;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #fff;
  display: flex;
  align-items: center;
  box-sizing: border-box;
}

.form-input:active {
  background-color: #f5f5f5;
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  border: 1px solid #e0e0e0;
  border-radius: 10rpx;
  padding: 20rpx;
  font-size: 28rpx;
  line-height: 1.5;
  box-sizing: border-box;
}

.sick-editor-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
}

.sick-editor-btn {
  padding: 16rpx 40rpx;
  font-size: 30rpx;
  border-radius: 10rpx;
  border: none;
}

.sick-editor-btn.cancel {
  background-color: #f5f5f5;
  color: #666;
}

.sick-editor-btn.confirm {
  background-color: #007AFF;
  color: white;
}

/* 删除按钮样式 */
.delete-btn {
  background-color: #ff3b30;
  color: white;
  font-size: 22rpx;
  padding: 6rpx 12rpx;
  margin-left: 0;
  border-radius: 6rpx;
  border: none;
  height: auto;
  line-height: 1.5;
}

.delete-btn:active {
  background-color: #d70015;
}

/* 删除确认弹窗样式 */
.delete-confirm-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1199;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-confirm-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.delete-confirm-content {
  position: relative;
  width: 80%;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.delete-confirm-header {
  text-align: center;
  margin-bottom: 30rpx;
}

.delete-confirm-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.delete-confirm-body {
  text-align: center;
  margin-bottom: 40rpx;
}

.delete-confirm-message {
  font-size: 30rpx;
  color: #666;
  line-height: 1.5;
}

.delete-confirm-actions {
  display: flex;
  justify-content: center;
  gap: 40rpx;
}

.delete-confirm-btn {
  padding: 20rpx 60rpx;
  font-size: 32rpx;
  border-radius: 10rpx;
  border: none;
  min-width: 160rpx;
}

.delete-confirm-btn.cancel {
  background-color: #f5f5f5;
  color: #666;
}

.delete-confirm-btn.confirm {
  background-color: #ff3b30;
  color: white;
}

.delete-confirm-btn.confirm:active {
  background-color: #d70015;
}
</style>